package com.webshop.servlet;

import com.webshop.Dao.UserDao;
import com.webshop.domain.user.User;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class CheckServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String status = "";
        String username = req.getParameter("username");
        if(username!=null && ((UserDao.checkUsername(username)==1))){
            status = status+"1";
        }
        else {
            status = status+"0";
        }

        String password = req.getParameter("password");
        if(password!=null&&((password.length()>=8)&&(password.length()<=16))){
            status = status+"1";
        }
        else status = status+"0";

        String email = req.getParameter("email");

        if(isEmail(email)){
            status  = status + "1";
        }else status = status+"0";
        resp.getWriter().print(status);
        if(status.equals("111")){
            User user = new User();
            user.setState("0");
            user.setModify(((req.getParameter("modify").equals("store")))?"store":"normal");
            user.setName(req.getParameter("name")==null?"noname":req.getParameter("name"));
            user.setUsername(username);
            user.setPassword(password);
            user.setBirthday(req.getParameter("date"));
            user.setTel(req.getParameter("tel"));
            user.setSex(req.getParameter("sex"));
            user.setEmail(req.getParameter("email"));
            UserDao.addUser(user);
        }
    }
    public static boolean isEmail(String string) {
        if (string == null)
            return false;
        String regEx1 = "^([a-z0-9A-Z]+[-|\\.]?)+[a-z0-9A-Z]@([a-z0-9A-Z]+(-[a-z0-9A-Z]+)?\\.)+[a-zA-Z]{2,}$";
        Pattern p;
        Matcher m;
        p = Pattern.compile(regEx1);
        m = p.matcher(string);
        if (m.matches())
            return true;
        else
            return false;
    }
}
